package com.hetang.maijiayun.adaptertools.b2cinterface.weidian.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.hetang.maijiayun.adaptertools.b2cinterface.weidian.domain.Status;
import com.hetang.maijiayun.adaptertools.b2cinterface.weidian.request.OrderListGetRequest;
import com.hetang.maijiayun.adaptertools.b2cinterface.weidian.response.OrderListGetResponse;
import com.hetang.maijiayun.adaptertools.b2cinterface.weidian.response.Response;
import com.hetang.maijiayun.adaptertools.utils.AdapterException;
import com.hetang.maijiayun.adaptertools.utils.AdapterExceptionErrorCode;
import com.hetang.maijiayun.adaptertools.utils.JsonUtil;

import net.sf.json.JSONObject;

public class WeidianClient {
    private static final String Version = "1.0";

    private static final String apiEntry = "http://api.vdian.com/api?";

    private static final String format = "json";
    
    private String sessionKey;

    public WeidianClient(String appId, String appSecret,String sessionKey){
        this.sessionKey=sessionKey;
    }
    public <T extends Response> T get(String method, String parames,Class<T> clazz) throws AdapterException{

        String url = apiEntry + getParamStr(method, parames);       
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response=null;
        try {
            response = client.execute(request);
        } catch (ClientProtocolException e1) {
        	 throw new AdapterException(
                     AdapterExceptionErrorCode.B2C_RPC_RESULT_ERROR_CODE,
                     "WeidianClient get ApiException : " +e1.getMessage());
        } catch (IOException e1) {
        	 throw new AdapterException(
                     AdapterExceptionErrorCode.B2C_RPC_RESULT_ERROR_CODE,
                     "WeidianClient get ApiException : " +e1.getMessage());
        }
        BufferedReader bufferedReader=null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
        } catch (IllegalStateException e) {
        	 throw new AdapterException(
                     AdapterExceptionErrorCode.B2C_RPC_RESULT_ERROR_CODE,
                     "WeidianClient get ApiException : " +e.getMessage());
        } catch (IOException e) {
        	 throw new AdapterException(
                     AdapterExceptionErrorCode.B2C_RPC_RESULT_ERROR_CODE,
                     "WeidianClient get ApiException : " +e.getMessage());
        }
        StringBuffer result = new StringBuffer();
        String line = "";
        try {
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
        } catch (IOException e) {
        	throw new AdapterException(
                    AdapterExceptionErrorCode.B2C_RPC_RESULT_ERROR_CODE,
                    "WeidianClient get ApiException : " +e.getMessage());
        }
        String getString=result.toString();
        JSONObject obj = JsonUtil.fromObjectNotNull(getString);
        
        String objresult="";
        if(result.indexOf("result")>=0){
            objresult = JsonUtil.getString(obj, "result");
        }
        String objstatus="";
        if(result.indexOf("status")>=0){
            objstatus = JsonUtil.getString(obj,"status");
        }

        Status status=JsonUtil.getBean(objstatus, Status.class);

        T t=JsonUtil.getBean(objresult, clazz);
        if(t != null && status!=null){
            t.setStatus_code(status.getStatus_code());
            t.setStatus_reason(status.getStatus_reason());
            t.setReturn_body(getString);
        }
        return t;
        
        
       
    }
    public String getParamStr(String method, String parames){
        String commonParams = getCommonParams(method);
        String str = "";
        try {
            str = URLEncoder.encode("param="+parames+"&public="+commonParams, "UTF-8")
                    .replace("%3A", ":")
                    .replace("%2F", "/")
                    .replace("%26", "&")
                    .replace("%3D", "=")
                    .replace("%3F", "?");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return str;
    }
    private String getCommonParams(String method){
        JSONObject publicMap = new JSONObject();
       publicMap.put("method", method);
       publicMap.put("access_token", this.sessionKey);
       publicMap.put("format",format);
       if(method.equals("vdian.order.list.get")){
           publicMap.put("version","1.1");  
       }else{
           publicMap.put("version",Version);   
       }
     
        return publicMap.toString();
    }

	public OrderListGetResponse execute(OrderListGetRequest req) throws WeidianException, AdapterException{
	    return get(req.getApiMethodName(),req.getJSONParams(),OrderListGetResponse.class);
    }
	
	public <T extends Response> T getResponse(String json,Class<T> clazz) throws AdapterException{
	    return JsonUtil.getBean(json, clazz);
	}

}
